package com.sinheldrin.musicplayer.player
{
	import com.sinheldrin.musicplayer.main.MainView;
	import com.sinheldrin.musicplayer.music.Music;
	import com.sinheldrin.musicplayer.music.Playlist;

	public class PlayerController
	{
		public function PlayerController(playerView:PlayerView)
		{
			_model = new PlayerModel();
			_view = playerView;
			_view.init(this);
			_youtubePlayer = new YoutubePlayerController(this);
		}
		
		public function init():void
		{
			_youtubePlayer.init();
		}
		
		private var _model:PlayerModel = null;
		[Bindable(event="modelChange")]
		public function get model():PlayerModel
		{
			return _model;
		}
		
		private var _view:PlayerView = null;
		public function get view():PlayerView
		{
			return _view;
		}
		
		public function play ():void
		{
			if (_model.isPlaying == false)
			{
				_youtubePlayer.play();
				_model.isPlaying = true;
			}
		}
		
		public function playMusic(music:Music):void
		{
			stop();
			_youtubePlayer.cue (music.VideoId);
			_model.currentMusic = music;
			play ();
		}
		
		public function pause ():void
		{
			if (_model.isPlaying == true)
			{
				_youtubePlayer.pause();
				_model.isPlaying = false;
			}
		}
		
		public function stop():void
		{
			if (_model.isPlaying == true)
			{
				_youtubePlayer.stop();
				_model.isPlaying = false;
			}
		}
		
		public function prev():void
		{
			var prevMusic:Music = null;
			if (model.random == true)
			{
				prevMusic = model.currentPlaylist.getRandomMusic();
			}
			else
			{
				prevMusic = model.currentPlaylist.prevMusic(model.currentMusic);
			}
			playMusic(prevMusic);
		}
		
		public function next():void
		{
			var nextMusic:Music = null;
			if (model.random == true)
			{
				nextMusic = model.currentPlaylist.getRandomMusic();
			}
			else
			{
				nextMusic = model.currentPlaylist.nextMusic(model.currentMusic);
			}
			playMusic(nextMusic);
		}
		
		public function autoPlay():void
		{
			model.isPlaying = false;
			if (model.autoPlay == true)
				next();
		}
		
		private var _youtubePlayer:YoutubePlayerController = null;
		
		public function setPlaylist(playlist:Playlist):void
		{
			_model.currentPlaylist = playlist;
		}
		
		public function getCurrentTime():Number
		{
			return _youtubePlayer.getCurrentTime();
		}
		
		public function getDuraction():Number
		{
			return _youtubePlayer.getDuraction();
		}
	}
}